package com.heaboy.emaidemo1.config;

import com.heaboy.emaidemo1.config.MailSenderInfo;
import lombok.extern.slf4j.Slf4j;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 单个邮箱发送器
 * 负责单个邮箱的邮件发送
 */
@Slf4j
public class EmailSender {
    
    private final EmailConfig config;
    private Session session;
    
    public EmailSender(EmailConfig config) {
        this.config = config;
        initSession();
    }
    
    /**
     * 初始化邮件会话
     */
    private void initSession() {
        Properties props = new Properties();
        
        // 设置邮件传输协议
        props.setProperty("mail.transport.protocol", "smtp");
        
        // 设置邮件服务器主机名
        props.setProperty("mail.host", config.getHost());
        props.setProperty("mail.port", config.getPort());
        
        // 设置是否安全验证
        props.setProperty("mail.smtp.auth", "true");
        
        // 设置SSL
        if (config.isSsl()) {
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.smtp.socketFactory.port", config.getPort());
        }
        
        // 设置编码
        props.setProperty("mail.smtp.charset", "UTF-8");
        
        // 创建认证器
        Authenticator authenticator = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        };
        
        // 创建会话
        session = Session.getInstance(props, authenticator);
        session.setDebug(false);
    }
    
    /**
     * 发送邮件
     */
    public boolean send(MailSenderInfo mailInfo) {
        try {
            // 创建消息
            Message message = new MimeMessage(session);
            
            // 设置发件人
            message.setFrom(new InternetAddress(config.getUsername()));
            
            // 设置收件人
            if (mailInfo.getToAddress() != null && !mailInfo.getToAddress().trim().isEmpty()) {
                String[] toAddresses = mailInfo.getToAddress().split(",");
                for (String toAddress : toAddresses) {
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress.trim()));
                }
            }
            
            // 设置抄送人
            if (mailInfo.getCcAddress() != null && !mailInfo.getCcAddress().trim().isEmpty()) {
                String[] ccAddresses = mailInfo.getCcAddress().split(",");
                for (String ccAddress : ccAddresses) {
                    message.addRecipient(Message.RecipientType.CC, new InternetAddress(ccAddress.trim()));
                }
            }
            
            // 设置密送人
            if (mailInfo.getBccAddress() != null && !mailInfo.getBccAddress().trim().isEmpty()) {
                String[] bccAddresses = mailInfo.getBccAddress().split(",");
                for (String bccAddress : bccAddresses) {
                    message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bccAddress.trim()));
                }
            }
            
            // 设置主题
            message.setSubject(mailInfo.getSubject());
            
            // 设置内容
            message.setContent(mailInfo.getContent(), "text/html;charset=UTF-8");
            
            // 发送邮件
            Transport.send(message);
            
            log.info("邮件发送成功 - 使用邮箱: {}", config.getName());
            return true;
            
        } catch (Exception e) {
            log.error("邮件发送失败 - 邮箱: {}, 错误: {}", config.getName(), e.getMessage());
            return false;
        }
    }
    
    /**
     * 检查邮箱是否可用
     */
    public boolean isAvailable() {
        return config.isEnabled();
    }
    
    /**
     * 获取邮箱配置
     */
    public EmailConfig getConfig() {
        return config;
    }
}

